package com.yc.testupload.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 数据迁移Servlet
 * 提供API接口用于触发wenku表和file表数据到素材表的迁移
 */
@WebServlet(name = "migrationServlet", value = "/api/migrate")
public class MigrationServlet extends HttpServlet {
    
    private static final Logger logger = LogManager.getLogger(MigrationServlet.class);
    private static ExecutorService executorService;
    private static boolean migrationInProgress = false;
    
    @Override
    public void init() throws ServletException {
        super.init();
        // 初始化线程池，用于异步执行迁移任务
        executorService = Executors.newSingleThreadExecutor();
        logger.info("MigrationServlet初始化完成，线程池已创建");
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/json;charset=UTF-8");
        logger.info("[请求入口] 收到数据迁移请求");
        
        // 检查是否有迁移任务正在进行
        if (migrationInProgress) {
            logger.warn("数据迁移任务正在进行中，请稍后再试");
            sendJsonResponse(response, false, "数据迁移任务正在进行中，请稍后再试", -1);
            return;
        }
        
        // 获取迁移类型参数
        String migrateType = request.getParameter("type");
        if (migrateType == null) {
            migrateType = "all";
        }
        
        // 创建final副本供lambda使用
        final String finalMigrateType = migrateType;
        
        // 标记迁移任务开始
        migrationInProgress = true;
        
        // 异步执行迁移任务
        executorService.submit(() -> {
            try {
                logger.info("开始执行异步数据迁移任务，类型: {}", finalMigrateType);
                
                if ("wenku".equals(finalMigrateType)) {
                    // 只迁移wenku表数据 - MigrationUtil类已移除
                    logger.info("wenku数据迁移功能已移除");
                } else if ("file".equals(finalMigrateType)) {
                    // 只迁移file表数据 - MigrationUtil类已移除
                    logger.info("file数据迁移功能已移除");
                } else {
                    // 迁移所有数据 - MigrationUtil类已移除
                    logger.info("所有数据迁移功能已移除");
                }
                
            } catch (Exception e) {
                logger.error("数据迁移任务执行异常: {}", e.getMessage(), e);
            } finally {
                // 标记迁移任务结束
                migrationInProgress = false;
                logger.info("数据迁移任务已完成，类型: {}", finalMigrateType);
            }
        });
        
        // 立即返回响应，表示任务已开始执行
        sendJsonResponse(response, true, "数据迁移任务已开始执行，请稍后查看日志确认完成情况", 0);
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/json;charset=UTF-8");
        
        // 返回当前迁移任务状态
        String status = migrationInProgress ? "in_progress" : "idle";
        String message = migrationInProgress ? "数据迁移任务正在进行中" : "当前无数据迁移任务";
        
        sendJsonResponse(response, true, message, status.equals("idle") ? 0 : 1);
    }
    
    /**
     * 发送JSON格式的响应
     */
    private void sendJsonResponse(HttpServletResponse response, boolean success, String message, int id) throws IOException {
        PrintWriter out = response.getWriter();
        try {
            out.println("{\n" +
                        "  \"success\": " + success + ",\n" +
                        "  \"message\": \"" + message + "\",\n" +
                        "  \"id\": " + id + "\n" +
                        "}");
        } finally {
            out.close();
        }
    }
    
    @Override
    public void destroy() {
        // 关闭线程池
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
            logger.info("线程池已关闭");
        }
        logger.info("MigrationServlet已销毁");
        super.destroy();
    }
}